/*
 * Copyright (C) 2010 Peter Schönhofen
 *
 * This file is part of the Akkad Compiler Framework.
 *
 * The Akkad Compiler Framework is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */

package hu.anaxo.akkad.processor

import collection.mutable.ListBuffer
import util.parsing.input.NoPosition
import hu.anaxo.akkad.vm._

/**
 * Generic translator
 */

abstract class Translator {

  /**
   * Translate syntax tree
   *
   * @param syntax syntax tree
   * @param scopes scopes
   *
   * @return instructions
   */

  protected def realTranslate(syntax: Syntax): List[Instruction]

  /**
   * Translate syntax tree (wrapper)
   *
   * @param syntax syntax tree
   * @param scopes scopes
   *
   * @return instructions
   */

  def translate(syntax: Syntax): List[Instruction] =
    try {
      realTranslate(syntax)
    } catch {
      case exception: Fault =>
        if (exception.position == NoPosition)
          throw Fault(exception.getMessage, syntax.pos)
        else
          throw exception
    }

  /**
   * Resolve label references
   *
   * @param program unresolved code
   *
   * @return resolved code
   */

  protected def resolve(program: List[Instruction]) = {

    // determine values of labels

    var result: ListBuffer[Instruction] = new ListBuffer
    for (instruction <- program)
      instruction match {
        case Define(label) =>
          label.resolve(result.length)
        case instruction =>
          result += instruction
      }

    // return result

    result.toList
  }
}